﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
using System.Xml;
using System.Xml.Serialization;
using bmapi.Controllers;
using Newtonsoft.Json;

namespace bmapi.HelperClass
{
    public class AssistFun
    {
        /// <summary>
        /// 对象转json
        /// </summary> 
        /// <param name="obj"></param>
        /// <returns></returns>
        public static HttpResponseMessage toJson(Object obj)
        {
            String str;
            if (obj is String || obj is Char)
            {
                str = obj.ToString();
            }
            else
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                str = serializer.Serialize(obj);
            }
            HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
            return result;
        }

        /// <summary>
        /// 将datable转换为List<T>
        /// </summary>
        /// <typeparam name="T">返回的数据类型</typeparam>
        /// <param name="dt">datable</param>
        /// <returns>List<T></returns>
        public static List<T> DataTableToList<T>(DataTable dt) where T : class, new()
        {
            //创建一个属性的列表    
            List<PropertyInfo> prlist = new List<PropertyInfo>();
            //获取TResult的类型实例  反射的入口    
            Type t = typeof(T);
            //获得TResult 的所有的Public 属性 并找出TResult属性和DataTable的列名称相同的属性(PropertyInfo) 并加入到属性列表     
            Array.ForEach<PropertyInfo>(t.GetProperties(), p => { if (dt.Columns.IndexOf(p.Name) != -1) prlist.Add(p); });
            //创建返回的集合    
            List<T> oblist = new List<T>();
            foreach (DataRow row in dt.Rows)
            {
                
                //创建TResult的实例    
                T ob = new T();
                //找到对应的数据  并赋值    
                prlist.ForEach(p => {
                    if (row[p.Name] != DBNull.Value)
                        p.SetValue(ob, row[p.Name], null);
                });


                //放入到返回的集合中    
                oblist.Add(ob);
            }
            return oblist;
        }

        /// <summary>
        /// DataRow转Object
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dr"></param>
        /// <returns></returns>
        public static T DataRowToObject<T>(DataRow dr)
        {

            if (dr == null)
            {
                return default(T);
            }

            T model = (T)Activator.CreateInstance(typeof(T));
            PropertyInfo[] propertyInfos = model.GetType().GetProperties();

            for (int i = 0; i < dr.Table.Columns.Count; i++)
            {
                if (dr[propertyInfos[i].Name] == DBNull.Value)
                    propertyInfos[i].SetValue(model, null, null);
                else
                    propertyInfos[i].SetValue(model, dr[propertyInfos[i].Name], null);

                //if (propertyInfos[i] != null && dr[i] != DBNull.Value)
                //    propertyInfos[i].SetValue(model, dr[propertyInfos[i].Name], null);
                //else continue;
            }

           
            return model;
        }


        public static HttpResponseMessage DataTableToJson(DataTable dt)
        {
            string str = string.Empty;
            str = JsonConvert.SerializeObject(dt);
            HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
            return result;
        }

        public class JsonToObject
        {

            public static Object JsonTObj(String json, Type t)
            {
                try
                {
                    System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(t);
                    using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
                    {

                        return serializer.ReadObject(ms);
                    }
                }
                catch
                {
                    return null;
                }
            }

        }

        //比较两个值的大小
        public static int GetMax(int x, int y)
        {
            if (x > y)
                return x;
            else
                return y;
        }

        /// <summary>
        /// 将两个列不同的DataTable合并成一个新的DataTable
        /// </summary>
        /// <param name="dt1">表1</param>
        /// <param name="dt2">表2</param>
        /// <param name="DTName">合并后新的表名</param>
        /// <returns></returns>
        public static DataTable UniteDataTable(DataTable dt1, DataTable dt2, string DTName)
        {
            DataTable dt3 = dt1.Clone();
            for (int i = 0; i < dt2.Columns.Count; i++)
            {
                dt3.Columns.Add(dt2.Columns[i].ColumnName);
            }
            object[] obj = new object[dt3.Columns.Count];

            for (int i = 0; i < dt1.Rows.Count; i++)
            {
                dt1.Rows[i].ItemArray.CopyTo(obj, 0);
                dt3.Rows.Add(obj);
            }
            if (dt1.Rows.Count >= dt2.Rows.Count)
            {
                for (int i = 0; i < dt2.Rows.Count; i++)
                {
                    for (int j = 0; j < dt2.Columns.Count; j++)
                    {
                        dt3.Rows[i][j + dt1.Columns.Count] = dt2.Rows[i][j].ToString();
                    }
                }
            }
            else
            {
                DataRow dr3;
                for (int i = 0; i < dt2.Rows.Count - dt1.Rows.Count; i++)
                {
                    dr3 = dt3.NewRow();
                    dt3.Rows.Add(dr3);
                }
                for (int i = 0; i < dt2.Rows.Count; i++)
                {
                    for (int j = 0; j < dt2.Columns.Count; j++)
                    {
                        dt3.Rows[i][j + dt1.Columns.Count] = dt2.Rows[i][j].ToString();
                    }
                }
            }
            dt3.TableName = DTName; //设置DT的名字
            return dt3;
        }
        public static DataTable UniteDataTables(DataTable dt1, DataTable dt2)
        {
            DataTable dt3 = dt1.Clone();
            dt3.Rows.Clear();
            object[] obj = new object[dt3.Columns.Count];
            for (int i = 0; i < dt1.Rows.Count; i++)
            {
                dt1.Rows[i].ItemArray.CopyTo(obj, 0);
                dt3.Rows.Add(obj);
            }
            for (int i = 0; i < dt2.Rows.Count; i++)
            {
                dt2.Rows[i].ItemArray.CopyTo(obj, 0);
                dt3.Rows.Add(obj);
            }
            return dt3;
        }
        /// <summary>
        /// 将数组转string
        /// </summary>
        /// <param name="ints"></param>
        /// <returns></returns>
        public static string ArryToString(string[] ints)
        {
            string res = "";
            for (int i = 0; i < ints.Length; i++)
            {
                res += ints[i] + ",";
            }
            return res.Substring(0, res.LastIndexOf(','));
        }

        /// <summary>
        /// 去除不必要的转义字符
        /// </summary>
        /// <param name="res"></param>
        /// <returns></returns>
        public static string RemoveChar(string res, string url)
        {
            res = res.Replace(@"\t", "");
            res = res.Replace(@"\", "");
            if (url.Contains("win2008"))
                res = res.Substring(1, res.Length - 2);
            return res;
        }

        /// <summary>
        /// 将一个对象序列化为XML字符串
        /// </summary>
        /// <param name="o">要序列化的对象</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>序列化产生的XML字符串</returns>
        public static string XmlSerialize(object o, Encoding encoding)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                XmlSerializeInternal(stream, o, encoding);

                stream.Position = 0;
                using (StreamReader reader = new StreamReader(stream, encoding))
                {
                    return reader.ReadToEnd();
                }
            }
        }

        /// <summary>
        /// obj序列化xml 
        /// </summary> 
        /// <param name="stream"></param>
        /// <param name="o"></param>
        /// <param name="encoding"></param>
        public static void XmlSerializeInternal(Stream stream, object o, Encoding encoding)
        {
            if (o == null)
                throw new ArgumentNullException("o");
            if (encoding == null)
                throw new ArgumentNullException("encoding");

            XmlSerializer serializer = new XmlSerializer(o.GetType());

            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            settings.NewLineChars = "\r\n";
            settings.Encoding = encoding;
            settings.IndentChars = "    ";

            using (XmlWriter writer = XmlWriter.Create(stream, settings))
            {
                serializer.Serialize(writer, o);
                writer.Close();
            }
        }

        /// <summary>
        /// 数组string[]转list<double>
        /// </summary>
        /// <param name="str">string[]数组</param>
        /// <returns></returns>
        public static List<double> stringToListdouble(string[] str)
        {
            List<double> vals = new List<double>();
            for (int j = 0; j < str.Length; j++)
            {
                if (str[j] == null)
                {
                    vals.Add(0);
                }
                else
                {
                    vals.Add(Convert.ToDouble((str[j])));
                }
            }
            return vals;
        }


    }
}